const { app, Menu, Tray, BrowserWindow, globalShortcut, ipcMain, session } = require('electron');
const path = require('path');
const fs = require('fs');

let aglobalShortcut = globalShortcut
let win;
let tray = null;
let isOpen = true;

// 窗口大小配置文件路径
//const configPath = path.join(app.getPath('userData'), 'window-config.json');

// 加载窗口配置
function loadWindowConfig() {
  //try {
  //  if (fs.existsSync(configPath)) {
  //    const data = fs.readFileSync(configPath, 'utf8');
  //    return JSON.parse(data);
  //  }
  //} catch (err) {
  //  console.error('加载窗口配置失败:', err);
  //}
  // 默认配置
  return { width: 350, height: 200 };
}

// 保存窗口配置
function saveWindowConfig(config) {
  //try {
  //  fs.writeFileSync(configPath, JSON.stringify(config, null, 2), 'utf8');
  //  console.log('窗口配置已保存:', config);
  //} catch (err) {
  //  console.error('保存窗口配置失败:', err);
  //}
}

function createWindow() {
  // 加载上次的窗口大小
  const windowConfig = loadWindowConfig();
  
  // 创建窗口并加载页面
  win = new BrowserWindow({
    width: windowConfig.width,
    height: windowConfig.height,
    minWidth: 100,  // 最小宽度
    minHeight: 50, // 最小高度
    transparent: true,
    icon: path.join(__dirname, 'icon.ico'),
    frame: false,
    alwaysOnTop: true,
    resizable: true, // 允许调整大小
    webPreferences: {
      nodeIntegration: true,
      contextIsolation: false,
      webSecurity: false // 关闭web安全策略，允许跨域和自定义请求头
    }
  })

  // 获取会话对象
  const ses = win.webContents.session;
  
  // 拦截所有请求并添加必要的请求头
  ses.webRequest.onBeforeSendHeaders({ urls: ['http://hq.sinajs.cn/*', 'https://hq.sinajs.cn/*'] }, (details, callback) => {
    // 为新浪财经API请求添加 Referer 和其他必要的头
    details.requestHeaders['Referer'] = 'https://finance.sina.com.cn/';
    details.requestHeaders['Origin'] = 'https://finance.sina.com.cn';
    details.requestHeaders['User-Agent'] = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36';
    
    callback({ requestHeaders: details.requestHeaders });
  });

  // 修改响应头，允许跨域访问
  ses.webRequest.onHeadersReceived({ urls: ['http://hq.sinajs.cn/*', 'https://hq.sinajs.cn/*'] }, (details, callback) => {
    const responseHeaders = details.responseHeaders || {};
    responseHeaders['Access-Control-Allow-Origin'] = ['*'];
    responseHeaders['Access-Control-Allow-Headers'] = ['*'];
    responseHeaders['Access-Control-Allow-Methods'] = ['*'];
    
    callback({ responseHeaders });
  });

  win.loadURL(`file://${__dirname}/index.html`);

  win.setMenu(null)

  win.on('close', (event) => {
    // 保存窗口大小
    const bounds = win.getBounds();
    
    win.hide();
    win.setSkipTaskbar(true);
    event.preventDefault();
  });
  
  tray = new Tray(path.join(__dirname, 'icon.ico'));
  win.on('show', () => {
    // this.tray.setHighlightMode('always')
  })
  win.on('hide', () => {
    // this.tray.setHighlightMode('never')
  })
 
  const contextMenu = Menu.buildFromTemplate([{
    label: '退出',
    click: () => {
      win.destroy()
      app.quit()
    }
  }])
  tray.setContextMenu(contextMenu)
  tray.on('click', () => {
    win.isVisible() ? win.hide() : win.show()
    win.isVisible() ? win.setSkipTaskbar(false) : win.setSkipTaskbar(true);
  })
}

// 处理窗口调整大小
ipcMain.on('resize-window', (event, { width, height }) => {
  if (win) {
    win.setSize(Math.round(width), Math.round(height));
  }
});

// 处理保存窗口大小
ipcMain.on('save-window-size', (event, { width, height }) => {
  saveWindowConfig({ width, height });
});

// 处理恢复窗口大小
ipcMain.on('restore-window-size', (event) => {
  const config = loadWindowConfig();
  if (win) {
    win.setSize(config.width, config.height);
  }
});

// 处理来自渲染进程的关闭窗口请求
ipcMain.on('close-app', () => {
  if (win) {
    win.destroy();
  }
  app.quit();
});

function reg(){
   const ret = aglobalShortcut.register('Alt+Q', () => {
   if(isOpen){
    win.hide();
    isOpen = !isOpen;
   }else{
    win.show();
    isOpen = !isOpen;
   }
  })
}

app.on('ready', createWindow);

app.on('ready', reg);

app.on('window-all-closed', () => {
  // Unregister a shortcut.
  aglobalShortcut.unregister('Alt+Q')
  aglobalShortcut.unregisterAll()
  if (process.platform !== 'darwin') {
    app.quit();
  }
});

app.on('activate', () => {
  if (win === null) {
    createWindow();
  }
});
